import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import SettingLayout from '@/component/setting/Layout';
import SettingStyle from '@/page/setting/setting.scss';
import AccountTable from '@/component/setting/AccountTable';
import { message, Input, Switch, Spin } from 'antd';
import _ from 'lodash';
import MModal from '@/component/common/MModal';

import ApiHelper from '@/store/ApiHelper';
import { admin_list, modify_admin, add_admin, delete_admin } from '@/constants/ApiTypes';
import AdminAuthTypes from '@/constants/AdminAuthTypes';
import format from '@/tool/format';
const mConfirm = MModal.confirm;
import helper from '@/tool/helper';

class AddAccountModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired
    };
    defaultState = {
        manageAccount: '',
        managePwd: '',
        manageName: '',
        rules: [],
        spinning: false
    };
    state = this.defaultState;
    //构造数组控制switch
    buildRules = () => {
        let _rules = [];
        AdminAuthTypes.forEach(val => {
            _rules.push({ id: val.id, name: val.name, checked: false });
        });
        this.setState({ rules: _rules });
    };
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
            this.buildRules();
        }
    }
    managerAccountChange = e => {
        this.setState({
            manageAccount: e.target.value
        })
    };
    managerNameChange = e => {
        this.setState({
            manageName: e.target.value
        })
    };
    managerPwdChange = e => {
        this.setState({
            managePwd: e.target.value
        })
    };
    accountModifyRightsSubmit = async () => {
        const { manageAccount, manageName, managePwd } = this.state;
        if (format.trim(manageAccount) == '') {
            this.manageAccount.focus();
            return message.warn('请填写管理员账号！', 1.5);
        }
        if (format.trim(manageName) == '') {
            this.manageName.focus();
            return message.warn('请填写管理员姓名！', 1.5);
        }
        if (managePwd == '') {
            this.managePwd.focus();
            return message.warn('请填写管理员密码！', 1.5);
        }
        if (managePwd.length < 6) {
            this.managePwd.refs.input.select();
            return message.warn('管理员密码长度必须大于等于6位！', 1.5);
        }
        if (managePwd.length > 16) {
            this.managePwd.refs.input.select();
            return message.warn('管理员密码长度必须小于等于16位！', 1.5);
        }

        let rules = [];
        this.state.rules.forEach(val => {
            if (val.checked) {
                rules.push(val.id);
            }
        });

        this.setState({ spinning: true });
        const data = {
            account: manageAccount,
            name: manageName,
            password: managePwd,
            rules: rules.join(',')
        };

        const result = await ApiHelper.requestPost(add_admin, data);
        this.setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '管理员添加成功' });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    switchOnChange = (checked, name) => {
        let rules = this.state.rules.map(val => {
            if (val.name == name) val.checked = checked;
            return val;
        });
        this.setState({ rules });
    };
    isChecked = name => {
        const result = _.find(this.state.rules, { name });
        if (result === undefined) return false;
        return result.checked;
    };
    render() {
        const { manageAccount, managePwd, manageName } = this.state;
        const { visible, onClose } = this.props;
        const { switchOnChange, isChecked } = this;
        const makeSwitch = name => <Switch checked={isChecked(name)} onChange={checked => switchOnChange(checked, name)} />;
        return (
            <MModal showMask visible={visible} onClose={onClose} width={770} height={helper.fixHeight(610)} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={SettingStyle['account-modal-wrap']}>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员账号:</span>
                            <Input value={manageAccount} ref={input => this.manageAccount = input} onChange={ this.managerAccountChange } placeholder="请输入管理员账号" />
                        </div>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员姓名:</span>
                            <Input value={manageName} ref={input => this.manageName = input} onChange={ this.managerNameChange } placeholder="请输入管理员姓名" />
                        </div>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员密码:</span>
                            <Input value={managePwd} ref={input => this.managePwd = input} onChange={ this.managerPwdChange } placeholder="请输入管理员密码" />
                        </div>
                        <h6>更改权限</h6>
                        <div className={SettingStyle['account-modify-button-group']}>
                            <table>
                                <thead/>
                                <tbody>
                                    <tr>
                                        <td>房源</td>
                                        <td>{makeSwitch('房源')}</td>
                                        <td>维修</td>
                                        <td>{makeSwitch('维修')}</td>
                                    </tr>
                                    <tr>
                                        <td>合同</td>
                                        <td>{makeSwitch('合同')}</td>
                                        <td>财务</td>
                                        <td>{makeSwitch('财务')}</td>
                                    </tr>
                                    <tr>
                                        <td>人员</td>
                                        <td>{makeSwitch('人员')}</td>
                                        <td>金融</td>
                                        <td>{makeSwitch('金融')}</td>
                                    </tr>
                                    <tr>
                                        <td>智能锁</td>
                                        <td>{makeSwitch('智能锁')}</td>
                                        <td>设置</td>
                                        <td>{makeSwitch('设置')}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div className={SettingStyle['account-submit-button']}>
                            <a className={SettingStyle['submit-btn']} href="javascript:void(0);" onClick={this.accountModifyRightsSubmit}>新增</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );

    }
}

class AccountInfoModal extends Component {
    constructor(props) {
        super(props);
    }
    static propTypes = {
        visible: PropTypes.bool,
        onClose: PropTypes.func.isRequired,
        admin_id: PropTypes.any,
        account: PropTypes.string,
        rules: PropTypes.string
    };
    defaultState = {
        managePwd: '',
        manageName: '',
        spinning: false,
        newRules: []
    };
    state = this.defaultState;
    componentWillReceiveProps(nextProps) {
        if (nextProps.visible) {
            this.setState(this.defaultState);
            this.buildRules(nextProps.rules);
        }
    }
    //构造数组控制switch
    buildRules = rules => {
        const old_rules = rules.split(',');
        let _rules = [];
        AdminAuthTypes.forEach(val => {
            if (_.indexOf(old_rules, `${val.id}`) > -1) {
                _rules.push({ id: val.id, name: val.name, checked: true });
            } else {
                _rules.push({ id: val.id, name: val.name, checked: false });
            }
        });
        this.setState({ newRules: _rules });
    };
    managerAccountChange = e => {
        this.setState({
            manageAccount: e.target.value
        })
    };
    managerNameChange = e => {
        this.setState({
            manageName: e.target.value
        })
    };
    managerPwdChange = e => {
        this.setState({
            managePwd: e.target.value
        })
    };
    accountModifyRightsSubmit = async () => {
        const { manageName, managePwd } = this.state;
        if (manageName.length > 0 && format.trim(manageName) == '') {
            this.manageName.refs.input.select();
            return message.warn('管理员姓名不能为纯空格！', 1.5);
        }
        if (managePwd.length < 6 && managePwd.length > 0) {
            this.managePwd.refs.input.select();
            return message.warn('管理员密码长度必须大于等于6位！', 1.5);
        }
        if (managePwd.length > 16 && managePwd.length > 0) {
            this.managePwd.refs.input.select();
            return message.warn('管理员密码长度必须小于等于16位！', 1.5);
        }
        this.setState({
            spinning: true
        });

        let rules = [];
        this.state.newRules.forEach(val => {
            if (val.checked) {
                rules.push(val.id);
            }
        });

        this.setState({ spinning: true });
        const data = {
            admin_id: this.props.admin_id,
            name: manageName,
            password: managePwd,
            rules: rules.join(',')
        };

        const result = await ApiHelper.requestPost(modify_admin, data);
        this.setState({ spinning: false });
        if (result.status) {
            MModal.success({ title: '操作成功', content: '管理员修改成功' });
            this.props.onClose(true);
        } else {
            MModal.success({ title: '操作失败', content: result.info });
        }
    };
    switchOnChange = (checked, name) => {
        let newRules = this.state.newRules.map(val => {
            if (val.name == name) val.checked = checked;
            return val;
        });
        this.setState({ newRules });
    };
    isChecked = name => {
        const result = _.find(this.state.newRules, { name });
        if (result === undefined) return false;
        return result.checked;
    };
    render() {
        const { account } = this.props;
        const { managePwd, manageName } = this.state;
        const { visible, onClose } = this.props;
        const { switchOnChange, isChecked } = this;
        const makeSwitch = name => <Switch checked={isChecked(name)} onChange={checked => switchOnChange(checked, name)} />;
        return (
            <MModal showMask visible={visible} onClose={onClose} width={770} height={helper.fixHeight(610)} zIndex={101}>
                <Spin tip="loading" spinning={this.state.spinning} delay={150}>
                    <div className={SettingStyle['account-modal-wrap']}>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员账号:</span>
                            <Input style={{ borderRadius: 0 }} value={account} disabled />
                        </div>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员姓名:</span>
                            <Input style={{ borderRadius: 0 }} value={manageName} ref={input => this.manageName = input} onChange={ this.managerNameChange } placeholder="请输入管理员姓名，留空不修改" />
                        </div>
                        <div className={SettingStyle['account-label-item']}>
                            <span>管理员密码:</span>
                            <Input style={{ borderRadius: 0 }} value={managePwd} ref={input => this.managePwd = input} onChange={ this.managerPwdChange } placeholder="请输入管理员密码，留空不修改" />
                        </div>
                        <h6>更改权限</h6>
                        <div className={SettingStyle['account-modify-button-group']}>
                            <table>
                                <thead/>
                                <tbody>
                                    <tr>
                                        <td>房源</td>
                                        <td>{makeSwitch('房源')}</td>
                                        <td>维修</td>
                                        <td>{makeSwitch('维修')}</td>
                                    </tr>
                                    <tr>
                                        <td>合同</td>
                                        <td>{makeSwitch('合同')}</td>
                                        <td>财务</td>
                                        <td>{makeSwitch('财务')}</td>
                                    </tr>
                                    <tr>
                                        <td>人员</td>
                                        <td>{makeSwitch('人员')}</td>
                                        <td>金融</td>
                                        <td>{makeSwitch('金融')}</td>
                                    </tr>
                                    <tr>
                                        <td>智能锁</td>
                                        <td>{makeSwitch('智能锁')}</td>
                                        <td>设置</td>
                                        <td>{makeSwitch('设置')}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div className={SettingStyle['account-submit-button']}>
                            <a className={SettingStyle['submit-btn']} href="javascript:void(0);" onClick={this.accountModifyRightsSubmit}>保存</a>
                        </div>
                    </div>
                </Spin>
            </MModal>
        );
    }
}

@observer class SettingAccount extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        adminList: [],
        AccountModalVisible: false,
        AddAccountModalVisible: false,
        AccountModalProps: {
            admin_id: 0
        },
        loading: true,
        spinning: false
    };
    async componentDidMount() {
        await this.getAdminList();
    }
    getAdminList = async () => {
        const result = await ApiHelper.requestPost(admin_list);
        if (result.status) {
            this.setState({
                adminList: result.info,
                loading: false,
                spinning: false
            });
        }
    };
    deleteAccount = admin_id => {
        mConfirm({
            title: '确定要删除该管理员吗？',
            titleStyle: { fontSize: 16 },
            width: 300,
            height: 177,
            content: '',
            okText: '是',
            cancelText: '否',
            okClassName: 'primary-btn-ok',
            cancelClassName: 'primary-btn-cancel',
            showTopClose: false,
            onOk: async () => {
                const data = { admin_id };
                const result = await ApiHelper.requestPost(delete_admin, data);
                if (result.status) {
                    MModal.success({ title: '操作成功', content: '管理员删除成功' });
                    this.getAdminList();
                } else {
                    MModal.success({ title: '操作失败', content: result.info });
                }
            },
            onCancel() {}
        });
    };
    closeAccountModal = refresh => {
        if (refresh) {
            this.setState({ spinning: true });
            this.getAdminList();
        }
        this.setState({  AccountModalVisible: false });
    };
    showAccountModal = (admin_id, account, rules) => {
        this.setState({
            AccountModalVisible: true,
            AccountModalProps: {
                admin_id,
                account,
                rules
            }
        });
    };
    showAddAccountModal = () => {
        this.setState({ AddAccountModalVisible: true });
    };
    closeAddAccountModal = (refresh = false) => {
        if (refresh) {
            this.setState({ spinning: true });
            this.getAdminList();
        }
        this.setState({ AddAccountModalVisible: false });
    };
    render() {
        const { spinning, adminList, AccountModalProps, AccountModalVisible, AddAccountModalVisible } = this.state;
        const columns = [
            { title: '管理员姓名', dataIndex: 'name', align: 'middle' },
            { title: '管理员账号', dataIndex: 'account', align: 'middle' },
            { title: '修改', render: (text, record, dataIndex) => <a onClick={() => this.showAccountModal(record.admin_id, record.account, record.rules)} className={SettingStyle['account-modify']} style={{ border: 'none', background: 'white' }}>修改</a> },
            { title: '竖线', render: () => <span>|</span> },
            { title: '删除', render: (text, record, dataIndex) => <a onClick={() => this.deleteAccount(record.admin_id)} className={SettingStyle['account-delete']} style={{ border: 'none', background: 'white' }}>删除</a> }
        ];
        return (
            <SettingLayout loading={this.state.loading}>
                <div className={SettingStyle['account-wrap']}>
                    <div className={SettingStyle['account-add']}>新增管理员<span className={SettingStyle['top-nav-plus']}><a onClick={this.showAddAccountModal} href="javascript:void(0);" /></span></div>
                    <hr className={SettingStyle['account-hr']}/>
                    <Spin spinning={ spinning }>
                        <AccountTable columns={columns} dataSource={adminList} />
                    </Spin>
                    <div className={SettingStyle['account-modal']}>
                        <AccountInfoModal visible={AccountModalVisible} onClose={this.closeAccountModal} {...AccountModalProps}/>
                    </div>
                    <div className={SettingStyle['account-modal']}>
                        <AddAccountModal visible={AddAccountModalVisible} onClose={this.closeAddAccountModal} />
                    </div>
                </div>
            </SettingLayout>
        );
    }
}

export default SettingAccount;